import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:smart_shop/constant/constant.dart';
import 'package:smart_shop/utils/colorUtils.dart';

/// 个人详情
class My extends StatefulWidget {
  const My({super.key});

  @override
  State<My> createState() => _MyState();
}

class _MyState extends State<My>
    with AutomaticKeepAliveClientMixin, SingleTickerProviderStateMixin {
  late int maxLen = 10;

  late double height = 60;

  late ScrollController _controller;

  late double offset = 0;

  List<Container> createContainer(BuildContext context) {
    final List<Container> list = [];
    for (var i = 0; i < maxLen; i++) {
      list.add(Container(
        decoration: const BoxDecoration(
            color: Colors.white,
            border: BorderDirectional(
                bottom: BorderSide(color: Color.fromRGBO(88, 88, 100, 0.08)))),
        height: height,
        padding: const EdgeInsets.symmetric(horizontal: 10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Center(
                child: Text('设置$i',
                    style: TextStyle(
                        fontFamily: 'PingFangSC-Regular',
                        fontSize: 20,
                        color: ColorUtils.fromHex('#212121'),
                        fontWeight: FontWeight.normal))),
            Center(
              child: Icon(
                Icons.chevron_right,
                size: 12,
                color: ColorUtils.fromHex('#959595'),
              ),
            )
          ],
        ),
      ));
    }
    return list;
  }

  @override
  void initState() {
    super.initState();
    _controller = ScrollController();
    _controller.addListener(() {
      setState(() {
        offset = _controller.offset;
      });
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  Color getColor() {
    if (offset <= 0) {
      return Colors.transparent;
    }
    return const Color.fromARGB(255, 255, 255, 255);
  }

  Color getFontColor() {
    if (offset <= 0) {
      return ColorUtils.fromHex('#FFFFFF');
    }
    return const Color.fromRGBO(33, 33, 33, 1);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Material(
      child: CustomScrollView(
        controller: _controller,
        slivers: [
          SliverAppBar(
            centerTitle: true,
            titleSpacing: 0,
            // 底部阴影
            // elevation: 0,
            title: Text('我的',
                style: TextStyle(
                    fontFamily: 'PingFangSC-Regular',
                    fontSize: 20,
                    color: getFontColor(),
                    fontWeight: FontWeight.normal)),
            snap: false,
            floating: false,
            pinned: true,
            backgroundColor: getColor(),
            expandedHeight: 183,
            collapsedHeight: 44 + MediaQuery.of(context).padding.top,
            flexibleSpace: LayoutBuilder(
              builder: (context, cons) {
                return FlexibleSpaceBar(
                    background: Container(
                  decoration: const BoxDecoration(
                    image: DecorationImage(
                        image: AssetImage('${Constant.ICON_URL}my.png'),
                        fit: BoxFit.fill),
                  ),
                  child: Padding(
                      padding: EdgeInsets.only(
                          top: (44 + MediaQuery.of(context).padding.top + 10),
                          left: 10,
                          right: 10),
                      child: SizedBox(
                        height: 100,
                        child: ClipRRect(
                          borderRadius: const BorderRadius.only(
                              topLeft: Radius.circular(9),
                              topRight: Radius.circular(9)),
                          child: Container(
                            decoration: const BoxDecoration(
                                color: Colors.white,
                                border: BorderDirectional(
                                    bottom: BorderSide(
                                        color: Color.fromRGBO(
                                            88, 88, 100, 0.08)))),
                            height: 100,
                            padding: const EdgeInsets.all(20),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                SizedBox(
                                  width: 80,
                                  height: 80,
                                  child: ClipRRect(
                                      borderRadius: const BorderRadius.all(
                                          Radius.circular(40.0)),
                                      child: Image.network(
                                        'https://cdn.uviewui.com/uview/album/2.jpg',
                                        fit: BoxFit.cover,
                                      )),
                                ),
                                Expanded(
                                    flex: 1,
                                    child: Container(
                                      padding: const EdgeInsets.only(
                                          left: 7, top: 10),
                                      child: Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.start,
                                        crossAxisAlignment:
                                            CrossAxisAlignment.center,
                                        children: [
                                          Align(
                                            alignment: Alignment.centerLeft,
                                            child: Text('赵今麦',
                                                style: TextStyle(
                                                    fontFamily:
                                                        'PingFangSC-Regular',
                                                    fontSize: 18,
                                                    color: ColorUtils.fromHex(
                                                        '#24242C'),
                                                    fontWeight:
                                                        FontWeight.normal)),
                                          ),
                                          Container(
                                            height: 7,
                                          ),
                                          Align(
                                            alignment: Alignment.centerLeft,
                                            child: Text('13589797',
                                                style: TextStyle(
                                                    fontFamily:
                                                        'PingFangSC-Regular',
                                                    fontSize: 18,
                                                    color: ColorUtils.fromHex(
                                                        '#24242C'),
                                                    fontWeight:
                                                        FontWeight.normal)),
                                          )
                                        ],
                                      ),
                                    )),
                                Center(
                                  child: Icon(
                                    Icons.chevron_right,
                                    size: 15,
                                    color: ColorUtils.fromHex('#1D1D2E'),
                                  ),
                                )
                              ],
                            ),
                          ),
                        ),
                      )),
                ));
              },
            ),
          ),
          SliverPersistentHeader(
            delegate: _SliverPersistentHeaderDelegate(
                maxHeight: maxLen * height + 20,
                minHeight: 60,
                child: Padding(
                  padding: const EdgeInsets.only(left: 10, right: 10),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: createContainer(context),
                  ),
                )),
          ),
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

class _SliverPersistentHeaderDelegate extends SliverPersistentHeaderDelegate {
  double maxHeight;
  double minHeight;
  Widget child;
  String statusBarMode = 'dark';

  _SliverPersistentHeaderDelegate(
      {required this.maxHeight, required this.minHeight, required this.child});

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    updateStatusBarBrightness(shrinkOffset);
    return SizedBox.expand(
      child: child,
    );
  }

  @override
  double get maxExtent => max<double>(minHeight, maxHeight);

  @override
  double get minExtent => min<double>(minHeight, maxHeight);

  @override
  bool shouldRebuild(_SliverPersistentHeaderDelegate oldDelegate) {
    // return maxHeight != oldDelegate.maxHeight ||
    //     minHeight != oldDelegate.minHeight ||
    //     child != oldDelegate.child;
    return true;
  }

  void updateStatusBarBrightness(shrinkOffset) {
    if (shrinkOffset > 60 && statusBarMode == 'dark') {
      statusBarMode = 'light';
      SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
        statusBarBrightness: Brightness.light,
        statusBarIconBrightness: Brightness.light,
      ));
    } else if (shrinkOffset <= 60 && statusBarMode == 'light') {
      statusBarMode = 'dark';
      SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
        statusBarBrightness: Brightness.dark,
        statusBarIconBrightness: Brightness.dark,
      ));
    }
  }

  Color makeStickyHeaderBgColor(shrinkOffset) {
    final int alpha =
        (shrinkOffset / (maxExtent - minExtent) * 255).clamp(0, 255).toInt();
    return Color.fromARGB(alpha, 255, 255, 255);
  }

  Color makeStickyHeaderTextColor(shrinkOffset, isIcon) {
    if (shrinkOffset <= 50) {
      return isIcon ? Colors.white : Colors.transparent;
    } else {
      final int alpha =
          (shrinkOffset / (maxExtent - minExtent) * 255).clamp(0, 255).toInt();
      return Color.fromARGB(alpha, 0, 0, 0);
    }
  }
}
